using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Axe
{
    public class ByteStream : Stream
    {
        private List<byte> mData = new List<byte>();
        private long mPosition;

        private long[] mReadBoundary = new long[2] {long.MinValue, long.MaxValue};

        #region public ByteStream()

        /// <summary>
        /// Initializes a new instance of the <see cref="T:ByteStream"/> class.
        /// </summary>
        public ByteStream()
        {
        }

        #endregion

        #region public ByteStream(byte[] data)

        /// <summary>
        /// Initializes a new instance of the <see cref="T:ByteStream"/> class.
        /// </summary>
        /// <mParam name="data">The data.</mParam>
        public ByteStream(byte[] data)
        {
            mData.AddRange(data);
        }

        #endregion

        #region public ByteStream(List<byte> data)

        /// <summary>
        /// Initializes a new instance of the <see cref="T:ByteStream"/> class
        /// with specified in <see cref="data"/> values
        /// </summary>
        /// <mParam name="data">The data.</mParam>
        public ByteStream(List<byte> data)
        {
            mData.AddRange(data);
        }

        #endregion

        #region public byte[] ToArray()

        /// <summary>
        /// Copies the elements of the current stream to a new array. 
        /// </summary>
        /// <returns></returns>
        public byte[] ToArray()
        {
            return mData.ToArray();
        }

        #endregion

        #region public void Append(ByteStream Stream)

        /// <summary>
        /// Appends to the current stream all contents of the specified stream.
        /// Read & Write position markers remains untouched.
        /// </summary>
        /// <mParam name="Stream">The stream, which is appending to current stream</mParam>
        /// <exception cref="ArgumentNullException">Stream is null</exception>
        public void Append(ByteStream stream)
        {
            if (stream == null)
                throw new ArgumentNullException("Appending stream is not assigned to an instance of objectt");

            mData.AddRange(stream.mData);
        }

        #endregion

        #region public bool EnsureCapacity(int length)

        /// <summary>
        /// Ensures that the capacity of current stream is larger or equal specified length
        /// </summary>
        /// <mParam name="length">The length.</mParam>
        /// <returns></returns>
        public bool EnsureCapacity(int length)
        {
            return mData.Count >= length;
        }

        #endregion

        #region public bool EnsureCapacity(int length)
        /// <summary>
        /// Ensures that the capacity of current stream is larger or equal specified length
        /// </summary>
        /// <mParam name="length">The length.</mParam>
        /// <returns></returns>
        public bool EnsureCapacity(long length)
        {
            return (long) mData.Count >= length;
        }

        #endregion

        #region public ByteStream GetRange(int startIndex,int count)

        /// <summary>
        /// Creates a shallow copy of a range of elements in the source stream.
        /// This method does not advance niether read not write pointer.
        /// Start index indicates absolute offset from the begin of stream.
        /// </summary>
        /// <mParam name="startIndex">The start index.</mParam>
        /// <mParam name="count">The count.</mParam>
        /// <returns></returns>
        /// <exception cref="ArgumentException">index is less than 0 or count is less than 0.</exception>
        /// <exception cref="ArgumentOutOfRangeException">index and count do not denote a valid range of elements in the stream.</exception>
        public ByteStream GetRange(int startIndex, int count)
        {
            return new ByteStream(mData.GetRange(startIndex, count));
        }

        #endregion

        #region public void RemoveRange(int index,int count)

        /// <summary>
        /// Removes a range of elements from the stream.
        /// This method does not advance niether read not write pointers.
        /// Start index indicates absolute offset from the begin of stream.
        /// </summary>
        /// <mParam name="index">The index.</mParam>
        /// <mParam name="count">The count.</mParam>
        /// <exception cref="ArgumentException">index is less than 0 or count is less than 0.</exception>
        /// <exception cref="ArgumentOutOfRangeException">index and count do not denote a valid range of elements in the stream.</exception>
        public void RemoveRange(int index, int count)
        {
            mData.RemoveRange(index, count);
        }

        #endregion

        #region public byte this[int index]
        public byte this[int index]
        {
            get
            {
                return mData[index];
            }
        } 
        #endregion


        #region public override string ToString()
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            long arrayLen = Length;

            for (long i = 0; i < arrayLen; i++)
            {
                sb.AppendFormat("{0:x}", mData[(int)i]);

                if (i < arrayLen)
                    sb.Append(" ");
            }

            return sb.ToString();
        } 
        #endregion

        #region Stream class Implementation

        #region public override bool CanRead

        /// <summary>
        /// When overridden in a derived class, gets a value indicating whether the current stream supports reading.
        /// </summary>
        /// <value></value>
        /// <returns>true if the stream supports reading; otherwise, false.</returns>
        public override bool CanRead
        {
            get { return true; }
        }

        #endregion

        #region public override bool CanSeek

        /// <summary>
        /// When overridden in a derived class, gets a value indicating whether the current stream supports seeking.
        /// </summary>
        /// <value></value>
        /// <returns>true if the stream supports seeking; otherwise, false.</returns>
        public override bool CanSeek
        {
            get { return true; }
        }

        #endregion

        #region public override bool CanWrite

        /// <summary>
        /// When overridden in a derived class, gets a value indicating whether the current stream supports writing.
        /// </summary>
        /// <value></value>
        /// <returns>true if the stream supports writing; otherwise, false.</returns>
        public override bool CanWrite
        {
            get { return true; }
        }

        #endregion

        #region public override void Flush()

        /// <summary>
        /// No action is performed for this implementation
        /// </summary>
        public override void Flush()
        {
        }

        #endregion

        #region public override long Length

        /// <summary>
        /// Gets the length in bytes of the stream.
        /// </summary>
        /// <value></value>
        /// <returns>A long value representing the length of the stream in bytes.</returns>
        public override long Length
        {
            get { return mData.Count; }
        }

        #endregion

        #region public override long Position
        /// <summary>
        /// Gets or sets the position within the current stream.
        /// </summary>
        /// <value></value>
        /// <returns>The current position within the stream.</returns>
        /// <exception cref="C:ArgumentOutOfRangeException">value is less than 0 or greater than stream length</exception>
        public override long Position
        {
            get { return mPosition; }
            set
            {
                if (value > Length)
                    throw new ArgumentOutOfRangeException("Position", value, "Position beyond end of stream");
                if (value < 0)
                    throw new ArgumentOutOfRangeException("Position", value, "Position can not be less zero");

                mPosition = value;
            }
        }

        #endregion

        #region public override int Read(byte[] buffer, int offset, int count)

        /// <summary>
        /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
        /// </summary>
        /// <mParam name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</mParam>
        /// <mParam name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</mParam>
        /// <mParam name="count">The maximum number of bytes to be read from the current stream.</mParam>
        /// <returns>
        /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
        /// </returns>
        /// <exception cref="T:System.ArgumentException">The sum of offset and count is larger than the buffer length. </exception>
        /// <exception cref="T:System.ArgumentNullException">buffer is null. </exception>
        /// <exception cref="T:System.ArgumentOutOfRangeException">offset or count is negative. </exception>
        public override int Read(byte[] buffer, int offset, int count)
        {
            if (buffer == null)
                throw new ArgumentNullException("Buffer is null");
            if (offset < 0)
                throw new ArgumentOutOfRangeException("offset", offset, "Offset is negative");
            if (count < 0)
                throw new ArgumentOutOfRangeException("count", offset, "Count is negative");

            if (EnsureCapacity(Position + count + offset) == false)
                throw new ArgumentOutOfRangeException("Stream capacity is not enough to read specified bytes");

            if (buffer.Length < count)
                throw new ArgumentOutOfRangeException(
                    "Destination buffer length is less, than specified maximum number of bytes to be read from the current stream");

            mData.CopyTo((int) (Position + offset), buffer, 0, count);
            Position += count;
            return count;
        }

        #endregion

        #region public override long Seek(long offset, SeekOrigin origin)

        /// <summary>
        /// When overridden in a derived class, sets the position within the current stream.
        /// </summary>
        /// <mParam name="offset">A byte offset relative to the origin parameter.</mParam>
        /// <mParam name="origin">A value of type <see cref="T:System.IO.SeekOrigin"></see> indicating the reference point used to obtain the new position.</mParam>
        /// <returns>
        /// The new position within the current stream.
        /// </returns>
        public override long Seek(long offset, SeekOrigin origin)
        {
            switch (origin)
            {
                case SeekOrigin.Begin:
                    Position = 0 + offset;
                    break;
                case SeekOrigin.Current:
                    Position = Position + offset;
                    break;
                case SeekOrigin.End:
                    Position = Length - offset;
                    break;
            }
            ;

            return Position;
        }

        #endregion

        #region public override void SetLength(long value)

        /// <summary>
        /// Allows to truncate the length of current stream. If truncation success, all position markers
        /// will check to point to valid elements of stream. If success, no action is performed, elsewhere,
        /// invalid markers will got next values:
        /// <para><list type="bullet">
        /// <item><term>Read position</term><description>will point to the begin of stream.</description></item>
        /// <item><term>Write position</term><description>will point to the end of stream.</description></item>
        /// </list></para>
        /// </summary>
        /// <mParam name="value">The desired length of the current stream in bytes.</mParam>
        /// <exception cref="ArgumentOutOfRangeException">Means that the specified value argument if greater than current stream length</exception>
        public override void SetLength(long value)
        {
            if (value > Length)
                throw new ArgumentOutOfRangeException(
                    "Cannot set stream length greater, than actual bytes count in the stream");

            if (value == Length)
                return; // No action is performed

            mData.RemoveRange((int) value, (int) (Length - value));

            if (Position >= Length)
                Position = 0;

            if (Position > Length)
                Position = Length;
        }

        #endregion

        #region public override void Write(byte[] buffer, int offset, int count)

        /// <summary>
        /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
        /// </summary>
        /// <mParam name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</mParam>
        /// <mParam name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</mParam>
        /// <mParam name="count">The number of bytes to be written to the current stream.</mParam>
        /// <exception cref="T:System.ArgumentNullException">buffer is null. </exception>
        /// <exception cref="T:System.ArgumentOutOfRangeException">offset or count is negative. </exception>
        public override void Write(byte[] buffer, int offset, int count)
        {
            if (buffer == null)
                throw new ArgumentNullException("Buffer is null");
            if (offset < 0)
                throw new ArgumentOutOfRangeException("offset", offset, "Offset is negative");
            if (count < 0)
                throw new ArgumentOutOfRangeException("count", offset, "Count is negative");

            byte[] actual_buffer;
            if (offset == 0 && buffer.Length == count)
            {
                actual_buffer = buffer;
            }
            else
            {
                actual_buffer = new byte[count];
                for (int i = 0; i < count; i++)
                    actual_buffer[i] = buffer[offset + i];
            }

            if (Position == Length)
            {
                mData.AddRange(actual_buffer);
            }
            else
            {
                mData.InsertRange((int) Position, actual_buffer);
            }

            Position += actual_buffer.Length;
        }

        #endregion

        #endregion
    }
}